# -*- coding: utf-8 -*-
import sys

sys.path.append('../..')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
from common.helper import Helper
import requests
import json
from threading import Thread
import pprint

class Spider(object):
    def __init__(self):
        self.mysql = MysqlClient()
        self.name = "平安少儿综合保险"

    def genProductInfo(self):

        plan = {
            "planA": {
                # 年龄段
                "year": [str(i) for i in range(0, 18)],
                # 有无社保
                "socialSec": ["Y", "N"],
                # 意外身故/伤残
                "accidentalDie": ["100000", "200000", "500000"],
                # 疾病身故
                "seriousDeath": ["0", "100000", "200000"],
                # 住院社会医疗保险内医疗
                "hospitalSocial": ["0", "60000", "100000"],
                # 少儿重大疾病
                "childrenDisease": ["0", "100000", "200000"],
                # 防癌医疗
                "defineCancer": ["0", "50000", "200000"],
                # 意外住院医疗
                "accidentHospital": ["0", "20000", "60000"],
                # 意外门诊医疗
                "accidentOutpatient": ["5000"],
                # 意外住院津贴
                "accidentAllowance": ["0", "100/天"],
                # 产品计划
                "plan": ["自定义"]
            },
            "planB": {
                # 年龄段
                "year": [str(i) for i in range(0, 18)],
                # 有无社保
                "socialSec": ["Y", "N"],
                # 意外身故/伤残
                "accidentalDie": ["500000"],
                # 疾病身故
                "seriousDeath": ["200000"],
                # 住院社会医疗保险内医疗
                "hospitalSocial": ["100000"],
                # 少儿重大疾病
                "childrenDisease": ["200000"],
                # 防癌医疗
                "defineCancer": ["200000"],
                # 意外住院医疗
                "accidentHospital": ["60000"],
                # 意外门诊医疗
                "accidentOutpatient": ["5000"],
                # 意外住院津贴
                "accidentAllowance": ["100/天"],
                # 产品计划
                "plan": ["豪华版"]
            },
            "planC": {
                # 年龄段
                "year": [str(i) for i in range(0, 18)],
                # 有无社保
                "socialSec": ["Y", "N"],
                # 意外身故/伤残
                "accidentalDie": ["200000"],
                # 疾病身故
                "seriousDeath": ["200000"],
                # 住院社会医疗保险内医疗
                "hospitalSocial": ["60000"],
                # 少儿重大疾病
                "childrenDisease": ["200000"],
                # 防癌医疗
                "defineCancer": ["200000"],
                # 意外住院医疗
                "accidentHospital": ["60000"],
                # 意外门诊医疗
                "accidentOutpatient": ["5000"],
                # 意外住院津贴
                "accidentAllowance": ["100/天"],
                #
                "plan": ["热销款"]
            }
        }

        for k in plan:
            for v in product(plan[k]["year"], plan[k]["socialSec"], plan[k]["accidentalDie"], plan[k]["seriousDeath"],
                             plan[k]["hospitalSocial"], plan[k]["childrenDisease"], plan[k]["defineCancer"],
                             plan[k]["accidentHospital"], plan[k]["accidentOutpatient"], plan[k]["accidentAllowance"],
                             plan[k]["plan"]):
                data = Helper.formatProductInfo(plan[k], v)
                self.mysql.cursor.execute(domain[self.name]["insert_sql"].format(**data))
                self.mysql._conn.commit()
                print(domain[self.name]["insert_sql"].format(**data))

    # 执行爬虫
    def requestJson(self, dt=None,mysql=None):
        if dt["plan"] == "豪华版":
            data = {"planClass": 0, "amountFormList": [
                {"suddennessDie": 500000, "sicknessDie": 200000, "childrenIll": 200000, "hospitalMedic": 60000,
                 "outpatientMedic": 5000, "hospitalAllowance": 100, "vaccineMedic": 100000, "cancerMedic": 200000},
                {"suddennessDie": 200000, "sicknessDie": 200000, "childrenIll": 200000, "hospitalMedic": 60000,
                 "outpatientMedic": 5000, "hospitalAllowance": 100, "vaccineMedic": 60000, "cancerMedic": 200000},
                {"suddennessDie": "200000", "sicknessDie": "0", "hospitalMedic": "60000", "outpatientMedic": "5000",
                 "hospitalAllowance": "0", "vaccineMedic": "60000", "childrenIll": "100000", "cancerMedic": "100000"}],
                    "beginDate": "2020-04-03", "insurantNum": "1", "birthDate": "{0}-01-01".format( str(int(2020-int(dt["year"])))),
                    "haveSocialInsurance": "P0254B19" if dt["socialSec"] == "N" else "P0254B18"}

        elif dt["plan"] == "热销款":
            data = {"planClass": 1, "amountFormList": [
                {"suddennessDie": 500000, "sicknessDie": 200000, "childrenIll": 200000, "hospitalMedic": 60000,
                 "outpatientMedic": 5000, "hospitalAllowance": 100, "vaccineMedic": 100000, "cancerMedic": 200000},
                {"suddennessDie": 200000, "sicknessDie": 200000, "childrenIll": 200000, "hospitalMedic": 60000,
                 "outpatientMedic": 5000, "hospitalAllowance": 100, "vaccineMedic": 60000, "cancerMedic": 200000},
                {"suddennessDie": "200000", "sicknessDie": "0", "hospitalMedic": "60000", "outpatientMedic": "5000",
                 "hospitalAllowance": "0", "vaccineMedic": "60000", "childrenIll": "100000", "cancerMedic": "100000"}],
                    "beginDate": "2020-04-03", "insurantNum": "1", "birthDate": "{0}-01-01".format( str(int(2020-int(dt["year"])))),
                    "haveSocialInsurance": "P0254B19" if dt["socialSec"] == "N" else "P0254B18"}

        else:

            data = {"planClass": 2, "amountFormList": [
                {"suddennessDie": 500000, "sicknessDie": 200000, "childrenIll": 200000, "hospitalMedic": 60000,
                 "outpatientMedic": 5000, "hospitalAllowance": 100, "vaccineMedic": 100000, "cancerMedic": 200000},
                {"suddennessDie": 200000, "sicknessDie": 200000, "childrenIll": 200000, "hospitalMedic": 60000,
                 "outpatientMedic": 5000, "hospitalAllowance": 100, "vaccineMedic": 60000, "cancerMedic": 200000},
                {"suddennessDie": dt["accidentalDie"], "sicknessDie": dt["seriousDeath"], "hospitalMedic": dt["hospitalSocial"], "outpatientMedic": "5000",
                 "hospitalAllowance": "0" if dt["accidentAllowance"] == "0" else dt["accidentAllowance"].replace("/天",""), "vaccineMedic": dt["accidentHospital"], "childrenIll": dt["childrenDisease"], "cancerMedic": dt["defineCancer"]}],
                    "beginDate": "2020-04-03", "insurantNum": "1", "birthDate": "{0}-01-01".format( str(int(2020-int(dt["year"])))),
                    "haveSocialInsurance": "P0254B19" if dt["socialSec"] == "N" else "P0254B18"}


        payload = json.dumps( data )
        r = requests.post( url = domain[self.name]["url"],headers=domain[self.name]["header"],data=payload)
        if r.status_code == 200 and "系统错误，请稍后再试。" not in r.text :
            pprint.pprint( r.json())
            if dt["plan"] == "豪华版":
                price = r.json()["quoteResult1"]["toaUserPremium"]
                data = {
                    "name": self.name,
                    "id": dt["id"],
                    "price": price
                }
            elif dt["plan"] == "热销款":
                price = r.json()["quoteResult2"]["toaUserPremium"]

                data = {
                    "name": self.name,
                    "id": dt["id"],
                    "price": price
                }
            else:
                price = r.json()["quoteResult3"]["toaUserPremium"]
                data = {
                    "name": self.name,
                    "id": dt["id"],
                    "price": price
                }
            mysql.updatePrice(data)
        else:
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 3
            }
            mysql.updateTask(data)
            print("\n/*更新产品价格失败:%d*/" % dt["id"])


    def main(self, mysql):

        while True:
            # 随机领取一条数据
            dt = mysql.randTask(self.name)
            if not dt:
                print("产品价格抓取完成~~~")
                return
            # 任务执行状态
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 1
            }
            mysql.updateTask(data)
            self.requestJson(dt, mysql)

    # 多线程
    def startProcess(self):
        for i in range(10):
            mysql = MysqlClient()
            t = Thread(target=self.main, args=(mysql,))
            t.start()
